package com.yeskery.nut.core;

import java.util.Arrays;
import java.util.Properties;

/**
 * 外部环境参数更新器
 * @author sprout
 * @version 1.0
 * 2023-06-04 02:29
 */
public class ExternalEnvironmentParameterUpdater {

    /** 键值对分割符 */
    private static final String KEY_VALUE_SEPARATOR = "=";

    /** 环境对象 */
    private final Environment environment;

    /** 启动参数 */
    private final String[] args;

    /**
     * 构建外部环境参数更新器
     * @param environment 环境对象
     * @param args 启动参数
     */
    public ExternalEnvironmentParameterUpdater(Environment environment, String[] args) {
        this.environment = environment;
        this.args = args;
    }

    /**
     * 更新环境参数
     */
    public void updateEnvironmentParameter() {
        Properties envProperties = environment.getEnvProperties();
        // 通过系统环境变量更新环境参数
        System.getenv().entrySet().stream()
                .filter(e -> envProperties.containsKey(e.getKey()))
                .forEach(e -> envProperties.setProperty(e.getKey(), e.getValue()));

        // 通过JVM参数更新环境参数
        System.getProperties().entrySet().stream()
                .filter(e -> envProperties.containsKey(e.getKey().toString()))
                .forEach(e -> envProperties.setProperty(e.getKey().toString(), e.getValue().toString()));

        // 通过启动参数更新环境参数
        Arrays.stream(args)
                .filter(arg -> arg.contains(KEY_VALUE_SEPARATOR))
                .map(arg -> arg.split(KEY_VALUE_SEPARATOR))
                .map(s -> new String[]{s[0].trim(), s[1].trim()})
                .filter(s -> envProperties.containsKey(s[0]))
                .forEach(s -> envProperties.setProperty(s[0], s[1]));
    }
}
